import Vue from 'vue'
import Router from 'vue-router'
import OverView from '@/view/Home'
import Login from '@/view/Login'
import NotFound from '@/view/NotFound'
import Home from '../view/OverView.vue'

import UserAdd from '../view/user/UserAdd.vue'
import UserManage from '../view/user/UserManage.vue'
import UserView from '../view/user/UserView.vue'

import CellData from '../view/CellData.vue'

Vue.use(Router)

const routes = [
  {
    path: '/login',
    name: '系统登录',
    component: Login,
    meta: { requiresAuth: false },
  },
  {
    path: '/',
    component: OverView,
    children: [
      {
        path: '',
        component: Home,
        name: '居民管理系统-概览'
      },
      {
        path: '/user',
        name: '居民录入',
        component: UserAdd,
      },
      {
        path: '/user/manage',
        name: '居民操作',
        component: UserManage,
      },
      {
        path: '/user/manage/:userID',
        name: '用户操作',
        component: UserManage,
      },
      {
        path: '/user/view',
        name: '信息概览',
        component: UserView,
      },
      // 分组管理
      {
        path: '/family',
        name: '家庭管理',
        component: CellData,
      },
      {
        path: '/tag/:ID',
        name: '家庭操作',
        component: CellData,
      },
      {
        path: '/tag',
        name: '分类管理',
        component: CellData,
      },
      {
        path: '/tag/:ID',
        name: '分类操作',
        component: CellData,
      },
      {
        path: '/allowance',
        name: '补助管理',
        component: CellData,
      },
      {
        path: '/allowance/:ID',
        name: '补助操作',
        component: CellData,
      },
      // 管理员信息
      {
        path: '/admin',
        name: '管理员信息',
        component: OverView,
      },
      {
        path: '/history',
        name: '操作记录',
        component: OverView,
      },
      {
        path: '/about',
        name: '关于系统',
        component: OverView,
      }
    ]
  },
  {
    path: '*',
    name: '页面未找到',
    component: NotFound,
    meta: { requiresAuth: false },
  },
]

// Routing logic
const router = new Router({
  routes,
})


router.beforeEach((to, from, next) => {
  const { requiresAuth = true } = to.meta
  if (requiresAuth) {
    const user = JSON.parse(sessionStorage.getItem('user')) || {}
    if (!user || !user.token) {
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      })
    } else {
      document.body.scrollTop = 0
      // document.documentElement.scrollTop = 0
      next()
    }
  } else {
    next()
  }
  document.title = to.name
})

export default router
